<template>
	<div>
		<div style="position:absolute; right: 20px;z-index:2">
			<a-button style="margin-left: 10px;" @click="filterTableStats(1)">打印/导出PDF</a-button>
			<a-button style="margin-left: 10px;" @click="filterTableStats(2)">导出</a-button>
		</div>
		<div id="settlement-info-page">
			<a-spin :spinning="spinning" :delay="120">
				<div class="container">
					<div class="toolbar">
						<a-form ref="formRef" :model="list">
							<h3 style="margin: 10px 0;text-align: center"><b>{{ (contract?.project?.name || '') + ' ' + (applyArgs.contract_name || '') + '结算单' }}</b></h3>
							<a-table :columns="isPrint ? innerColumns.filter(item => !!(tableStatsModal.stats.includes(item.key))) : innerColumns" :scroll="tableScroll" row-key="id" children-column-name="children" :pagination="false" :data-source="list" :loading="loading">
								<template #headerCell="{ column }">
									<template v-if="column.title.includes('\n')">
										<span>
											{{ column.title.split('\n')[0] }}<br />{{ column.title.split('\n')[1] }}
										</span>
									</template>
									<template v-else-if="column.title === 'up_per'">
										<span v-if="contract?.price_type === 2">
											浮动比率±(%)
										</span>
										<span v-else-if="contract?.price_type === 3">
											浮动价格(±)
										</span>
									</template>
								</template>
								<template #bodyCell="{ column, index, record }">
									<template v-if="column.key === 'append_subprice'">
										<!--										<a-form-item :name="[index, 'append_subprice']" :rules="{ required: true, message: '请输入' }">-->
										<!--											<a-input-number v-model:value="record.append_subprice" placeholder="请输入" :disabled="optDisabled" />-->
										<!--										</a-form-item>-->
										{{ record.append_subprice }}
									</template>
									<template v-else-if="column.key === 'use_position' && [1, 2, 3, 5].includes(list[0]?.settlement.ys_type)">
										<a-row :gutter="20">
											<a-col :span="24">
												<a-form-item :name="[index, 'use_position']" :rules="{ required: true, message: '请选择详细部位' }">
													<a-tree-select v-model:value="record.use_position" :dropdown-match-select-width="false" :show-search="true" placeholder="请选择详细部位" allow-clear tree-default-expand-all :tree-data="gonghaoTree" tree-node-filter-prop="label" style="width:100%" :disabled="optDisabled" @change="changeUsePosition(record)">
														<template #title="{ label }">{{ label }}</template>
													</a-tree-select>
												</a-form-item>
											</a-col>
										</a-row>
									</template>
									<template v-else-if="column.key === 'account_type_id'">
										<a-row :gutter="20">
											<a-col :span="24">
												<a-form-item :name="[index, 'account_type_id']" :rules="{ required: true, message: '核算分类' }">
													<a-select v-model:value="record.account_type_id" placeholder="请选择核算分类" :options="accountTypeOptions" option-filter-prop="label" :disabled="optDisabled"></a-select>
												</a-form-item>
											</a-col>
										</a-row>
									</template>
									<template v-else-if="column.key === 'expenditure_id'">
										<a-row :gutter="20">
											<a-col :span="24">
												<a-form-item :name="[index, 'expenditure_id']" :rules="{ required: true, message: '支出方向' }">
													<a-select v-model:value="record.expenditure_id" placeholder="请选择支出方向" :options="expenditureOptions" option-filter-prop="label" :disabled="optDisabled" allow-clear></a-select>
												</a-form-item>
											</a-col>
										</a-row>
									</template>
									<template v-else-if="column.key === 'brand'">
										<a-row :gutter="20">
											<a-col :span="24">
												<!--												<a-form-item :name="[index, 'brand']" :rules="{ required: true, message: '请输入品牌' }" :disabled="optDisabled">-->
												<!--													<a-input v-model:value="record.brand" placeholder="请输入品牌" :disabled="optDisabled" />-->
												<!--												</a-form-item>-->
												{{ record.brand }}
											</a-col>
										</a-row>
									</template>
								</template>
								<template #summary>
									<a-table-summary-row style="background-color:#f0f0f0;font-size:12px;font-weight:bold;">
										<a-table-summary-cell :col-span="formatTotalSpan(['apply_time', 'states', 'material_name'])" style="text-align: center">
											<a-typography-text type="danger">合计</a-typography-text>
										</a-table-summary-cell>
										<a-table-summary-cell v-if="list[0]?.settlement.ys_type === 2" :col-span="formatTotalSpan(['changdu', 'luodu', 'expected_location'])"></a-table-summary-cell>
										<!--								<a-table-summary-cell :col-span="11"></a-table-summary-cell>-->
										<!--										<a-table-summary-cell :col-span="8"></a-table-summary-cell>-->
										<a-table-summary-cell :col-span="formatTotalSpan(['model', 'unit', 'quantity', 'ys_quantity', 'ys_user', 'memo'])"></a-table-summary-cell>
										<a-table-summary-cell :col-span="formatTotalSpan('append_subprice')" style="text-align: center">{{ totalAmount.append_subprice }}</a-table-summary-cell>
										<a-table-summary-cell v-if="contract?.price_type !== 1 && contract?.price_type" :col-span="formatTotalSpan('up_per')" style="text-align: center">
											{{ contract.price_type === 3 ? totalAmount.up_per : '' }}
										</a-table-summary-cell>
										<a-table-summary-cell :col-span="formatTotalSpan('with_tax_subprice')" style="text-align: center">{{ totalAmount.with_tax_subprice }}</a-table-summary-cell>
										<a-table-summary-cell :col-span="formatTotalSpan('with_tax_amount')" style="text-align: center">{{ totalAmount.with_tax_amount }}</a-table-summary-cell>
										<a-table-summary-cell :col-span="formatTotalSpan('without_tax_subprice')" style="text-align: center">{{ totalAmount.without_tax_subprice }}</a-table-summary-cell>
										<a-table-summary-cell :col-span="formatTotalSpan('without_tax_amount')" style="text-align: center">{{ totalAmount.without_tax_amount }}</a-table-summary-cell>
										<a-table-summary-cell :col-span="formatTotalSpan('tax_amount')" style="text-align: center">{{ totalAmount.tax_amount }}</a-table-summary-cell>
										<a-table-summary-cell :col-span="formatTotalSpan(['tax', 'brand'])">
											<!--											<a-input-number v-model:value="totalAmount.amount" :min="0" addon-before="本次结算总额" placeholder="请输入金额" :disabled="optDisabled" />-->
											<div style="text-align: right">本次结算总额：{{ totalAmount.amount }}</div>
										</a-table-summary-cell>
									</a-table-summary-row>
								</template>
							</a-table>
						</a-form>
						<div>
							<h3 style="margin: 10px 0;"><b>单据信息</b></h3>
							<a-descriptions bordered size="middle">
								<a-descriptions-item label="合同号">{{ applyArgs.contract_name }}</a-descriptions-item>
								<a-descriptions-item label="供应商" :span="2">{{ applyArgs.supplier_name }}</a-descriptions-item>
								<a-descriptions-item label="结算附件下载">
									<!--								<a-button :href="list[0]?.settlement.file_path[0]?.url" target="_blank">下载附件</a-button><br />-->
									<!--								<span style="color:#ccc">{{ list[0]?.settlement.file_path[0]?.name }}</span>-->
									<a :href="list[0]?.settlement.file_path[0]?.url" target="_blank">{{ list[0]?.settlement.file_path[0]?.name }}</a>
								</a-descriptions-item>
								<a-descriptions-item label="合同附件" :span="2">
									<a :href="applyArgs.contract_file?.url" target="_blank">{{ applyArgs.contract_file?.name }}</a>
								</a-descriptions-item>
								<a-descriptions-item label="结算说明">
									{{ applyArgs.memo }}
								</a-descriptions-item>
								<a-descriptions-item label="审核人/审核时间">
									{{ applyArgs.auditor? (applyArgs.auditor + ' / ' + applyArgs.examine_time): '' }}
								</a-descriptions-item>
							</a-descriptions>
						</div>
						<div class="mt-5 text-center">
							<template v-if="!optDisabled">
								<a-button type="primary" @click="handleSave('save')">保存台账</a-button>
								<a-button type="primary" style="margin-left: 1rem" @click="handleSave('apply')">生成结算申请单</a-button>
							</template>
							<template v-else>
								<div class="flex">
									<div style="flex:1">
										<a-button type="default" @click="back">返回</a-button>
									</div>
								</div>
							</template>
						</div>
					</div>
				</div>
			</a-spin>
		</div>
		<a-modal v-model:visible="tableStatsModal.visible" :title="btnType == 1 ? '打印表单显示' : '导出表单显示'" :width="400" :body-style="{height:'400px',overflowY: 'auto'}" @ok="handlePrint">
			<a-checkbox-group v-model:value="tableStatsModal.stats">
				<a-row>
					<a-col v-for="(item) in checkColumns" :key="item.key" :span="24">
						<a-checkbox :value="item.value">{{ item.label }}</a-checkbox>
					</a-col>
				</a-row>
			</a-checkbox-group>
		</a-modal>
	</div>
</template>
<script setup>
import { useRoute, useRouter } from "vue-router";
import { computed, getCurrentInstance, onMounted, ref } from "vue";
import { printElement } from '../utils/exportData.js';
import { post, treeToList } from "@/utils/index.js";
import dayjs from "dayjs";
import { Modal } from "ant-design-vue";
const settleStatelist = [
	{ value: 1, label: "结算中" },
	{ value: 2, label: "已结算" },
	{ value: 3, label: "未知" }
];
const applyArgs = ref({
	file_path: [],
	contract_name: '',
	supplier_name: '',
	memo: null,
	contract_file: null,
})
const columns = [
	{
		title: "验收时间",
		dataIndex: "settlement",
		key: 'apply_time',
		sorter: false,
		ellipsis: true,
		align: "center",
		width: 150,
		customRender: ({ text, record, index, column }) => {
			return dayjs(text.apply_time).format("YYYY-MM-DD HH:mm:ss");
		}
	},
	{
		title: "状态",
		dataIndex: "settlement",
		key: 'states',
		sorter: false,
		// ellipsis: true,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return settleStatelist.filter(item => item.value === text.status)[0].label;
		}
	},
	{
		title: "材料名称",
		dataIndex: "material",
		key: 'material_name',
		sorter: false,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return text.name;
		}
	},
	{
		title: "规格型号",
		dataIndex: "model",
		key: 'model',
		sorter: false,
		// ellipsis: true,
		align: "center",
	},
	{
		title: "计量单位",
		dataIndex: "unit",
		key: 'unit',
		sorter: false,
		align: "center",
	},
	{
		title: "采购数量",
		dataIndex: "quantity",
		key: 'quantity',
		sorter: false,
		align: "center",
	},
	{
		title: "验收数量",
		dataIndex: "ys_quantity",
		key: 'ys_quantity',
		sorter: false,
		align: "center",
	},
	// {
	// 	title: "发货单编号",
	// 	dataIndex: "real_code",
	// 	sorter: false,
	// 	width: 150,
	// },
	// {
	// 	title: "验收单编号",
	// 	dataIndex: "ys_code",
	// 	sorter: false,
	// 	width: 150,
	// },
	{
		title: "验收人",
		dataIndex: "ys_user",
		key: 'ys_user',
		sorter: false,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return text?.fullname;
		}
	},
	// {
	// 	title: "核算分类",
	// 	dataIndex: "account_type_id",
	// 	sorter: false,
	// 	width: 150,
	// 	align: "center",
	// },
	// {
	// 	title: "使用部位",
	// 	dataIndex: "use_position",
	// 	sorter: false,
	// 	width: 200,
	// 	align: "center",
	// 	customRender: ({ text, record, index, column }) => {
	// 		return '';
	// 	}
	// },
	{
		title: "是否泵送（长度）",
		dataIndex: "changdu",
		key: 'changdu',
		sorter: false,
		align: "center",
	},
	{
		title: "申请塌落度（mm）",
		dataIndex: "luodu",
		key: 'luodu',
		sorter: false,
		align: "center",
	},
	{
		title: "预计浇筑部位",
		dataIndex: "expected_location",
		key: 'expected_location',
		sorter: false,
		align: "center",
	},
	// {
	// 	title: "支出方向",
	// 	dataIndex: "expenditure_id",
	// 	sorter: false,
	// 	width: 150,
	// 	align: "center",
	// },
	{
		title: "备注",
		dataIndex: "memo",
		key: 'memo',
		sorter: false,
		align: "center",
	},
	{
		title: "附加价",
		dataIndex: "append_subprice",
		key: 'append_subprice',
		sorter: false,
		align: "center",
	},
	{
		title: "up_per",
		dataIndex: "up_per",
		key: 'up_per',
		sorter: false,
		align: "center",
	},
	{
		title: "综合含税单价\n(元)",
		dataIndex: "with_tax_subprice",
		key: 'with_tax_subprice',
		sorter: false,
		align: "center",
	},
	{
		title: "含税总价\n(元)",
		dataIndex: "with_tax_amount",
		key: 'with_tax_amount',
		sorter: false,
		align: "center",
	},
	{
		title: "不含税单价\n(元)",
		dataIndex: "without_tax_subprice",
		key: 'without_tax_subprice',
		sorter: false,
		align: "center",
	},
	{
		title: "不含税总价\n(元)",
		dataIndex: "without_tax_amount",
		key: 'without_tax_amount',
		sorter: false,
		align: "center",
	},
	{
		title: "税额\n(元)",
		dataIndex: "tax_amount",
		key: 'tax_amount',
		sorter: false,
		align: "center",
	},
	{
		title: "税率",
		dataIndex: "tax",
		key: 'tax',
		sorter: false,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return text + '%';
		}
	},
	{
		title: "品牌",
		dataIndex: "brand",
		key: 'brand',
		sorter: false,
		align: "center",
		width: 150,
	},
];
const route = useRoute();
const contract_id = route.query.contract_id;
const isPrint = JSON.parse(route.query.print || "false");
const optDisabled = ref(true);
const contract = ref({});
const loading = ref(false);
const list = ref([]);
const accountTypeOptions = ref([]);
const expenditureOptions = ref([]);
const gonghaoTree = ref([]);
const totalAmount = ref({
	append_subprice: 0,
	with_tax_amount: 0,
	with_tax_subprice: 0,
	without_tax_amount: 0,
	without_tax_subprice: 0,
	tax_amount: 0,
	amount: null,
});
const innerColumns = computed(() => {
	let columnList = columns;
	if (contract.value.price_type === 1 || !contract.value.price_type) {
		columnList = columnList.filter(item => item.title !== "up_per");
	}
	if (list.value[0]?.settlement.ys_type !== 2) {
		columnList = columnList.filter(item => !["expected_location", 'changdu', 'luodu'].includes(item.key));
	}
	return columnList;
});
const spinning = ref(false);
const formRef = ref();
const formOther = ref();
const { proxy } = getCurrentInstance();
const router = useRouter();
const tableStatsModal = ref({
	loading: false,
	visible: false,
	stats: (route.query.stats || '').split(','),
})
const checkColumns = computed(() => {
	return innerColumns.value.map(item => {
		let label = item.title;
		if (item.title === 'up_per') {
			label = contract.value?.price_type === 2 ? '浮动比率±(%)' : '浮动价格(±)';
		}
		return { value: item.key, label };
	})
})
post("dictionary", { root_code: "ACCOUNT_TYPE" }).then(data => {
	accountTypeOptions.value = data || [];
});
post("dictionary", { root_code: "EXPENDITURE" }).then(data => {
	expenditureOptions.value = data;
});
onMounted(async () => {
	const result = await post(`settlement/material`, {
		settlement_id: route.params.id
	})
	const contractList = await post(`contract/all`, {
		contract_ids: result[0].contract_id,
	});
	contract.value = contractList[0] || {};
	applyArgs.value.contract_name = contract.value.name;
	applyArgs.value.supplier_name = contract.value.supplier?.company_name;
	applyArgs.value.contract_file = JSON.parse(contract.value.file_path || '[]')[0];
	applyArgs.value.memo = result[0]?.settlement.memo;
	applyArgs.value.auditor = result[0]?.settlement?.auditor?.fullname;
	applyArgs.value.examine_time = result[0]?.settlement?.examine_time;
	// 商砼
	if ([1, 2, 3, 5].includes(result[0]?.settlement.ys_type)) {
		const usePositions = await post("department/getTrees", { type: 4, parent_id: contract.value.project_id });
		gonghaoTree.value = usePositions;
	}
	for (const item of result) {
		Object.assign(item, item.record);
		// 商砼
		if ([1, 2, 3, 5].includes(item?.settlement.ys_type)) {
			if (item.position || item.gonghao_id) {
				const gonghaoList = treeToList(JSON.parse(JSON.stringify(gonghaoTree.value)), []);
				const use_position = gonghaoList.filter((i) => {
					return i.id === (item.position || item.gonghao_id)
				})[0]
				item.use_position = use_position.value;
			}
		}
	}
	totalAmount.value.append_subprice = parseFloat(result[0].settlement.append_subprice);
	totalAmount.value.with_tax_amount = parseFloat(result[0].settlement.with_tax_amount);
	totalAmount.value.with_tax_subprice = parseFloat(result[0].settlement.with_tax_subprice);
	totalAmount.value.without_tax_amount = parseFloat(result[0].settlement.without_tax_amount);
	totalAmount.value.without_tax_subprice = parseFloat(result[0].settlement.without_tax_subprice);
	totalAmount.value.tax_amount = parseFloat(result[0].settlement.tax_amount);
	totalAmount.value.amount = parseFloat(result[0].settlement.amount);
	if (contract.value.price_type === 2) {
		totalAmount.value.up_per = parseFloat(result[0].settlement.up_per);
	}
	list.value = result;
})
const tableScroll = computed(() => ({ x: document.documentElement.clientWidth - 650 }));

// 改变部位
function changeUsePosition(record) {
	if (!record.use_position) {
		record.gonghao_id = null;
		record.position = null;
		return;
	}
	const gonghao_id = record.use_position.split('-')[1];
	let position = record.use_position.split('-').slice(-1)[0];
	if (gonghao_id === position) {
		position = null;
	}
	record.gonghao_id = gonghao_id;
	record.position = position;
}
// 提交
function handleSave(save_type) {
	if (!list.value.length) {
		return proxy.$message.error('物料列表不能为空');
	}
	formRef.value
		.validate()
		.then(async () => {
			proxy.$message.destroy();
			if (!totalAmount.value.amount) {
				return proxy.$message.error('请输入结算总金额');
			}
			const data = {
				save_type,
				project_id: contract.value.project_id,
				contract_id: contract.value.id,
				ys_type: list.value[0]?.supplyOrder.ys_type,
				supplier_id: contract.value.supplier_id,
				...totalAmount.value,
				materials: JSON.stringify(list.value.map(item => {
					return {
						...item.material,
						material_id: item.material.id,
						supply_order_id: item.supply_order_id,
						time_unit: item.time_unit,
						use_item: item.time_unit,
						quantity: item.quantity,
						real_quantity: item.real_quantity,
						ys_quantity: item.ys_quantity,
						real_code: item.supplyOrder.code,
						ys_code: item.yanshou.code,
						gonghao_id: item.gonghao_id,
						position: item.position,
						memo: item.memo,
						record: { brand: item.material.brand },
						ys_opr_id: item.yanshou.opr_id,
						contract_id: contract.value.id,
					}
				})),
			}
			if (save_type === 'save') {
				spinning.value = true;
				await post("settlement/save", data);
				proxy.$message.success("保存成功", 1);
				spinning.value = false;
			} else {
				Modal.confirm({
					title: "操作确认?",
					content: "您确定申请结算吗，请确认",
					onOk() {
						spinning.value = true;
						post("settlement/save", data)
							.then(() => {
								spinning.value = false;
								proxy.$message.success("申请成功", 1);
								router.push('/settlement/apply');
							})
							.catch(err => {
								proxy.$message.error(err);
								spinning.value = false;
							});
					}
				});
			}
		})
		.catch(err => {
			spinning.value = false;
			proxy.$message.error(err.message || err);
		})
}
const btnType = ref(1)
const filterTableStats = (type) => {
	// type 1打印/导出PDF 2导出
	btnType.value = type
	tableStatsModal.value.visible = true;
	const query = route.query;
	if (query.stats) {
		tableStatsModal.value.stats = query.stats.split(',');
	} else {
		tableStatsModal.value.stats = checkColumns.value.map(item => item.value);
	}
}

const formatTotalSpan = (stats = []) => {
	if (typeof stats === 'string') {
		if (!isPrint) return 1;
		return tableStatsModal.value.stats.includes(stats) ? 1 : 0;
	} else {
		if (!isPrint) return stats.length;
		let len = 0;
		for (const item of stats) {
			len += tableStatsModal.value.stats.includes(item);
		}
		return len;
	}
}

const handlePrint = async () => {
	const query = {};
	if (tableStatsModal.value.stats.length) {
		query.stats = tableStatsModal.value.stats.join(',');
	}
	if (btnType.value === 1) {
		router.replace({ query })
		setTimeout(() => {
			printElement('settlement-info-page')
		}, 500)
	} else {
		const dates = await post("settlement/export/info", {
			id: route.params.id,
			keys: tableStatsModal.value.stats.join(','),
		});
		if (dates.url) window.location.href = dates.url;
	}
	
	tableStatsModal.value.visible = false;
	
}

// 返回
function back() {
	if (list.value[0].settlement.status === 1) {
		router.push('/settlement/apply');
	} else if (list.value[0].settlement.status === 2) {
		router.push('/settlement/history');
	}
}
</script>
<style scoped lang="scss">
.container {
	background: #fff;
	padding: 12px;
}

:deep(.ant-table-cell) .ant-form-item {
	margin-bottom: 0;
}

:deep(.ant-descriptions-title) {
	text-align: center;
}
</style>
